package com.gitee.magic.context.converter.list;

import java.util.ArrayList;
import java.util.List;

import com.gitee.magic.context.ConverterEditorUtils;
import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.json.JsonArray;
import com.gitee.magic.core.json.JsonObject;

/**
 * @author start
 */
public class ListvConverterEditor extends AbstractConverterEditor<String> {

	public ListvConverterEditor(Class<?> prototype) {
		super(prototype);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			Class<?> target=value.getClass();
			JsonArray arrays;
			if(target.equals(JsonObject.class)) {
				arrays=(JsonArray)value;
			}else {
				arrays=new JsonArray(String.valueOf(value));
			}
			List<Object> content=new ArrayList<>();
			for(int i=0;i<arrays.length();i++) {
				Object val=arrays.get(i);
				content.add(ConverterEditorUtils.restoreObject(getPrototype(), val));
			}
			setValue(content);
		}
	}

	@Override
	public String converter() {
		if (getSource() == null) {
			return null;
		}
		return getSource().toString();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setValue(Object v) {
		super.setValue(v);
		if(getValue()!=null) {
			List<Object> content = (List<Object>) getValue();
			JsonArray arrays = new JsonArray();
			for (Object val : content) {
				arrays.put(ConverterEditorUtils.converterObject(val));
			}
			setSource(arrays);
		}
	}

}
